<?php

namespace app\api\controller;

use think\Controller;
use think\Db;

class Product extends Base {

    /****************************************************************************
     * 接口方法
     ***************************************************************************/
    
    /**
     * 商品详情
     * @return json
     */
    public function productInfo() {
//        try {
            $productId  = input('product_id', 0, 'intval');
            $user_id    = input('user_id',0);
            $user       = Db::name('user')->where('id',$user_id)->find();
//            return json($user);
            //根据id查找审核通过并已上架的商品信息
            $product = self::getProductById($productId);
            if (!empty($product)) {
                // 用户评论
                $evaluate = self::getCommentByProductId($productId);
                if(!empty($evaluate)){
                    $comment = $evaluate[0];
                    $time = strtotime($evaluate[0]['time']);
                    $comment['time'] = date("Y/m/d",$time);
                }else{
                    $comment = [];
                }

                $supplier = self::getSupplier($product['supplier']);
                if(!empty($user)) {
                    $date = self::getSendDate($user['city'], $user['town'], $product['supplier']);
                    $collect = self::getCollect($productId,$user_id);
                }else{
                    $collect = 0;
                    $date = '暂无配送';
                }
                $supplier['date'] = $date;
                $res['supplier'] = $supplier;
                $product['suppliers'] = $supplier;
                $product['collect'] = $collect;
                $product['comment'] = $comment;
                $tax = Db::name('system_setting')->where(['id'=>1])->find();
                $product['tax'] = $tax['value'];//税率
                //评论总数
                $product['comment_count'] = count($evaluate);
                //获取商品详情页面的图片
                $product['list_image'] = self::getProductImageListByProductId($productId);
                $product['price'] = number_format($product['price'],2,'.','');
                $res = config('code.success');
                $res['data'] = $product;
            } else {
                $res = config('code.null');
                $res['data'] = [];
            }
//        } catch (\Exception $ex) {
//            $res = config('code.lose');
//            $res['data'] = [];
//        }
        return jsonReturn($res['status'], $res['msg'], $res['data']);
    }

    /**
     * 商品详情-配送时间
     * @return json
     */
    public function deliveryTime() {
        try {
            $data = input('request.');
//            return json($data);
            if (!validate('Product')->scene('delivery_time')->check($data)) {
                $res = config('code.error');
                $res['msg'] = validate('Product')->getError();
                $res['data'] = [];
            } else {
                Db::startTrans();
                // 1.通过用户邮编获取用户所在区域，再用用户所在区域id关联商户配送区域，获取匹配用户的配送时间
                $deliveryTime = self::getDeliveryTimeByUserIdSupplierId($data['user_id'], $data['supplier_id']);
                // 2.获取商户配送方式
                $type = Db::name('supplier')->where(['id' => $data['supplier_id']])->find();
                //根据配送方式获取用户区域的配送时间
                $time = self::getDeliveryTimeBySendTimeType($type['send_time_type'], $deliveryTime);
                
                $res = config('code.success');
                $res['data'] = $time;
            }
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = [];
        }
        return jsonReturn($res['status'], $res['msg'], $res['data']);
    }

    /**
     * 商品详情-(选择规格,立即订购,加入进货单,)
     * @return json
     */
    public function specifications() {
        try {
            $productId = input('product_id', 0, 'intval');
            $list = Db::name('product_specification')
                    ->field('id,is_default,product_id,packing_proportion,unit,specification,format(price,2) as price')
                    ->where(['product_id' => $productId,'flag'=>1])
                    ->select();
            $data = $list;
            $res = config('code.success');
            $res['data'] = $data;
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = [];
        }
        return jsonReturn($res['status'], $res['msg'], $res['data']);
    }

    /**
     * 商品详情-收藏
     * @return json
     */
    public function productCollect() {
        try {
            $userId = input('user_id', '', 'trim');
            $userId = input('user_id');
            $productId = input('product_id');

                if (empty($productId)) {
                    //参数异常，未获取到商品id
                    $res = config('code.mistake');
                } else {
                    $re = Db::name('user_collect_product')->where(['user_id'=>$userId,'product_id'=>$productId,'flag'=>1,'is_del'=>0])->find();
                    if(!empty($re)){
                        Db::name('user_collect_product')->where(['user_id'=>$userId,'product_id'=>$productId,'flag'=>1,'is_del'=>0])->update(['is_del'=>1]);
                        $res['status'] = 200;
                        $res['msg']    = '取消收藏';
                    }else{
                        //收藏商品
                        $arr['user_id'] = $userId;
                        $arr['product_id'] = $productId;
                        $arr['flag'] = 1;
                        $arr['collect_time'] = date("Y-m-d H:i:s");
                        $ok = Db::name('user_collect_product')->insert($arr);
                        $res = $ok ? config('code.success') : config('code.error');
                    }

                }
        } catch (\Exception $ex) {
            $res = config('code.lose');
        }
        return json($res);
    }

    /**
     * 商品所有评论
     * @return json
     */
    public function evaluate() {
        try{
            $productId = input('product_id', 0, 'intval');
            $type = input('type', 1, 'intval'); // 1：全部评论 2：低分评论 3：最新评论
            $page = input('page_no');
            $size = input('page_size',10,'intval');
            if (!in_array($type, [1, 2, 3])) {
                $type = 1;
            }
            if (empty($productId)) {
                $res = config('code.mistake');
                $res['data'] = [];
            } else {
                //根据type获取评论信息
                $re = self::getEvaluateByType($type, $productId,$size);
                $list = $re->toArray();
                foreach ($list['data'] as $key => $item) {
                    $list['data'][$key]['time'] = date('Y/m/d',strtotime($item['time']));
                }
                //获取全部评论平均分
                $score = Db::name('comment')->where(['product_id'=>$productId])->field('avg(star) as score')->find();
                $res = config('code.success');
                $res['data'] = $list['data'];
                $res['count'] = $list['total'];
                if(input('is_web')){
                    $res['html'] = $re->render();
                    $res['last_page'] = $list['last_page'];
                    $res['current_page'] = $list['current_page'];
                }
                $res['score'] = round($score['score'],2);
            }
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = $ex->getMessage();
        }
        exit(json_encode($res));
    }

    /**
     * 商品详情-产品参数
     * @return json
     */
    public function parameter() {
        try {
            $productId = input('product_id', 0, 'intval');
            if (empty($productId)) {
                $res = config('code.mistake');
                $res['data'] = [];
            } else {
                //获取商品参数信息
                $product = Db::name('product')->alias('a')
                                ->join('base_data b', 'a.brand_id=b.id', 'left')
                                ->join('base_data c', 'a.type_id=c.id', 'left')
                                ->field('a.name,a.is_shelves,a.stock,b.name as brand,b.name_english as brand_english,c.name as type,c.name_english as type_english')
                                ->where(['a.id' => $productId])->find();
                
                $res = config('code.success');
                $res['data'] = $product;
            }
        } catch (\Exception $ex) {
            $res = config('code.lose');
            $res['data'] = [];
        }
        return jsonReturn($res['status'], $res['msg'], $res['data']);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /***************************************************************************
     * 操作方法
     ****************************************************************************/

    /**
     * 根据用户id以及商户id获取配送时间
     * @param int $userId
     * @param int $supplierId
     * @return array
     */
    protected static function getDeliveryTimeByUserIdSupplierId($userId,$supplierId){
        $user = Db::name('user')->where(['id'=>$userId])->find();
//        var_dump($user);exit();
        switch ($user){
            case !empty($user['city']):
                $str = 'a.city=c.send_area';//用城市关联
                break;
            case !empty($user['town']):
                $str = 'a.town=c.send_area';//用乡镇关联
                break;
        }
        $data = Db::name('user')->alias('a')
                ->join('supplier_send_manage c', $str, 'left')
                ->where(['a.id' => $userId, 'c.supplier_id' => $supplierId])
                ->field('c.*')
                ->order('c.month asc')
                ->order('c.day asc')
                ->select();
//        echo Db::name('user')->getLastSql();exit;

        return $data;
    }
    
    /**
     * 获取商品详情图片
     * @param int $id
     * @return array
     */
    protected function getProductImageListByProductId($id){
        $list = Db::name('product_image')->alias('a')
                ->join('image b','a.image_id=b.id','left')
                ->where(['a.product_id'=>$id])
                ->field('a.*,b.name,b.image_url')
                ->select();
        $res['list_url'] = [];//轮播图片
        $res['info_url'] = [];//详情图片
        foreach ($list as $k=>$v){
            switch ($v['type']){
                case '1':
                    $res['list_url'][] = $v['image_url'];
                    break;
                case '0':
                    $res['info_url'][] = $v['image_url'];
                    break;
            }
            unset($list[$k]['image_url']);
        }
        return $res;
    }
    
    /**
     * 根据id获取商品信息
     * @param int $id 商品id
     * @param int $status 商品状态
     * @param int $shelves 是否上架
     * @return array
     */
    protected static function getProductById($id,$status=1,$shelves=1){
        $res = Db::name('product')->alias('a')
                    ->join('base_data b', 'a.category_id=b.id', 'left')
                    ->join('base_data c', 'a.type_id=c.id', 'left')
                    ->join('base_data d', 'a.small_type_id=d.id', 'left')
                    ->join('base_data e', 'a.brand_id=e.id', 'left')
                    ->join('product_specification f','a.id=f.product_id','left')
                    ->where(['a.id' => $id, 'a.status' => $status, 'a.is_shelves' => $shelves,'f.is_default'=>'1'])
                    ->field('a.id,a.name,a.description,a.supplier,'
                        . 'a.details,a.image,a.stock,a.origin,'
                        . 'a.sale_num,b.name as category,'
                        . 'b.name_english as category_english,'
                        . 'c.name as type,c.name_english as type_english,'
                        . 'd.name as small_type,d.name_english as small_type_english,'
                        . 'e.name as brand,e.name_english as brand_english,'
                        . 'f.packing_proportion,f.specification,f.id as fid,f.unit,f.price,a.is_include_tax,a.category_id')
                    ->find();
        $time  = date("Y-m-d H:i:s", time());
        $where = [
            'product_id'  => $res['id'],
            'status'      => 1,
            'start_time'  => ['<=',$time],
            'end_time'    => ['>=',$time]
        ];
        $count = Db::table('discount')
            ->where($where)
            ->count();
        if ($count>0){
            $res['is_discount'] = 1;
        }else{
            $res['is_discount'] = 0;
        }
        return $res;
    }
    protected static function getCollect($product_id,$user_id){
        $re = Db::name('user_collect_product')->where(['user_id'=>$user_id,'product_id'=>$product_id,'flag'=>1,'is_del'=>0])->find();
        if(!empty($re)){
            $collect = 1;
        }else{
            $collect = 0;
        }
        return $collect;
    }
    protected static function getSendDate($city,$twon,$supplier_id){
        $supplier = Db::name('supplier')->field('send_time_type')->where('id',$supplier_id)->find();
        $re = Db::name('supplier_send_manage')
            ->where('supplier_id',$supplier_id)
            ->where('flag',1)
            ->where('send_area',$city)
            ->whereOr('send_area',$twon)
            ->order('month asc')
            ->order('day asc')
            ->select();
        $day = date('d');
        $y = date('Y');
        $m = date('m');
        $d = date('d');
        if($supplier['send_time_type'] ==1){
            $week = date('w');
            if(count($re) == 1){
                if($week <= $re[0]['day']){
                    $time = ($re[0]['day'] - $week)*24*60*60;
                    $date = strtotime($y.'-'.$m.'-'.$d.' 00:00:00')+$time;
                }else{
                    $time = ( 7-($week-$re[0]['day']))*24*60*60;
                    $date = strtotime($y.'-'.$m.'-'.$d.' 00:00:00')+$time;
                }
            }else{
                $is_choose = false;
                foreach ($re as $k => $item) {
                    if ($item['day'] >= $week) {
                        $time = ($re[$k]['day'] - $week)*24*60*60;
                        $date = strtotime($y.'-'.$m.'-'.$d.' 00:00:00')+$time;
                        $is_choose = true;
                        break;
                    }
                }
                if(!$is_choose){
                    if(count($re) == 0){
                        $date = '暂无配送';
                    }else {
                        $time = (7 - ($week - $re[0]['day'])) * 24 * 60 * 60;
                        $date = strtotime($y . '-' . $m . '-' . $d . ' 00:00:00') + $time;
                    }
                }
            }

        }else{

            if(count($re) == 1){
                if($re[0]['day']>$day && $re[0]['month']>=$m){
//                    $date = strtotime($y.'-'.($m+1).'-'.$re[0]['day'].' 00:00:00');
                    $date = strtotime($y.'-'.$re[0]['month'].'-'.$re[0]['day'].' 00:00:00');
                }else{
                    $date = '暂无配送';
                }
            }else {
                $is_choose = false;
                foreach ($re as $k => $item) {
                    if (($item['day'] < $day && $item['month'] > $m)  ||($item['day'] > $day && $item['month'] >= $m)){
                        $date = strtotime($y.'-'.$re[$k]['month'].'-'.$re[$k]['day'].' 00:00:00');
                        $is_choose = true;
                        break;
                    }
                    /*if ($item['day'] > $day && $item['month'] >= $m) {
                        $date = strtotime($y.'-'.$re[$k]['month'].'-'.$re[$k]['day'].' 00:00:00');
                        $is_choose = true;
                        break;
                    }*/
                }
                if(!$is_choose){
                    if(count($re) == 0){
                        $date = '暂无配送';
                    }else {
//                        $date = strtotime($y . '-' . ($m + 1) . '-' . $re[0]['day'] . ' 00:00:00');
                        $date = '暂无配送';
                    }
                }
            }
        }
        if($date != '暂无配送') {
            return date('Y-m-d', $date);
        }else{
            return $date;
        }
    }

    /**
     * 按照配送方式获取配送日期
     * @param int $type
     * @param array $arr
     * @return array
     */
    protected static function getDeliveryTimeBySendTimeType($type, $arr) {
//        var_dump($type);
        switch ($type) {

            case 1:
                //按周配送
                $data = self::getSendTimeWeek($arr);
                break;
            case 2:
                //按月配送
                $data = self::getSendTimeMonth($arr);
                break;
        }
        return $data;
    }

    /**
     * 获取按周配送的日期
     * @param array $arr
     * @return array
     */
    protected static function getSendTimeWeek($arr) {
        $brr = [];
        $week           =   array("一","二","三","四","五","六","日");
        $week_english   =   array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
        foreach ($arr as $k => $v) {
            $day['time'] =  '周' . $week[$v['day'] -1 ];
            $day['time_english'] = $week_english[$v['day']-1];
            $brr[] = $day;
//            for ($i = 1; $i <= date('t'); $i++) {
//                $str = date('Y') . '-' . date('m') . '-' . $i;
//                $time = strtotime($str);
//                $week = date('w', $time);
//                if ($week == $v['day']) {
//                    $day['time'] = date('m') . '月' . $i . '日';
//                    $day['time_english'] = date('F') . ' ' . $i;
//                    $brr[] = $day;
//                }
//            }
        }
        return $brr;
    }

    /**
     * 获取按月配送的日期
     * @param array $arr
     * @return array
     */
    protected static function getSendTimeMonth($arr) {
        $brr = [];
        $month_english = array("","Jan.","Feb.","Mar.","Apr.","May.","Jun.","Jul.","Aug.","Sept.","Oct.","Nov.","Dec.");
        foreach ($arr as $k => $v) {
            $day['time'] = $v['month'] . '月' . $v['day'] . '日';
            $day['time_english'] =  $month_english[$v['month']]. ' ' . $v['day'];
            $brr[] = $day;
        }
        return $brr;
    }

    /**
     * 获取评论数据信息
     * @param int $type
     * @param int $id
     * @return array
     */
    protected static function getEvaluateByType($type, $id,$size) {
        if(0 >= $size){
            $size = 10;
        }
//        echo ($type);exit;
        switch ($type) {
            case 1:
                //查询商品所有评论
                $re = Db::name('comment')->alias('a')
                        ->join('user b', 'a.user_id=b.id', 'left')
                        ->where(['a.product_id' => $id, 'a.comment_type' => '0'])
                        ->group('a.id')
//                    ->field('a.*,b.image,b.name as user_name,b.addr as area_name')

                        ->field("a.comment,a.star,date_format(a.time,'%Y-%m-%d') as time,b.image,b.name as user_name,b.addr as area_name")
                        ->order('a.time desc')
                        ->paginate($size,false,['path'=>'javascript:ajaxPage([PAGE])','type'=>'BootstrapDetailed','var_page'=>'page_no']);
                break;
            case 2:
//                var_dump(2);
                //查询所有低分评论
                $re = Db::name('comment')->alias('a')
                        ->join('user b', 'a.user_id=b.id', 'left')
                        ->where(['a.product_id' => $id, 'a.comment_type' => '0'])
                        ->where('a.star' ,'<', 3)
                        ->group('a.id')
//                        ->field('a.*,b.image,b.name as user_name,b.addr as area_name')
                        ->field("a.comment,a.star,date_format(a.time,'%Y-%m-%d') as time,b.image,b.name as user_name,b.addr as area_name")
                        ->order('a.time desc')
                        ->paginate($size,false,['path'=>'javascript:ajaxPage([PAGE])','type'=>'BootstrapDetailed','var_page'=>'page_no']);
               break;
            case 3:
                //查询最新评论
                $re = Db::name('comment')->alias('a')
                        ->join('user b', 'a.user_id=b.id', 'left')
                        ->where(['a.product_id' => $id, 'a.comment_type' => '0'])
                        ->group('a.id')
                        ->order(['a.time' => 'desc'])
//                        ->field('a.*,b.image,b.name as user_name,b.addr as area_name')
                        ->field("a.comment,a.star,date_format(a.time,'%Y-%m-%d') as time,b.image,b.name as user_name,b.addr as area_name")
                        ->order('a.time desc')
                        ->paginate($size,false,['path'=>'javascript:ajaxPage([PAGE])','type'=>'BootstrapDetailed','var_page'=>'page_no']);
                break;
        }
        return $re;
    }
    
    /**
     * 根据商家id获取商家的评论
     * @param int $id
     * @return array
     */
    protected static function getCommentByProductId($id){
        $comment =Db::name('comment')->alias('a')
                ->join('user b','a.user_id=b.id','left')
                ->where(['a.product_id'=>$id,'a.comment_type'=>'0'])
                ->field('a.id,a.comment,a.star,b.name,a.time,b.image,b.addr')
                ->order('a.time desc')
                ->select();
        return $comment;
    }

    protected static function getSupplier($id){
        $re = Db::name('supplier')
            ->field('name as supplier_name,id as supplier_id,image,is_open')
            ->where('id',$id)
            ->find();
        return $re;
    }
}
